package com.vanke.kotlin_mvp.addedit

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import com.vanke.kotlin_mvp.R
import com.vanke.kotlin_mvp.data.Injection
import com.vanke.kotlin_mvp.util.ActivityUtils
import kotlinx.android.synthetic.main.activity_add_edit.*


class AddEditTaskActivity : AppCompatActivity() {

    private lateinit var addEditTaskPresenter: AddEditTaskPresenter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_add_edit)

        setSupportActionBar(toolbar)
        supportActionBar?.let {
            it.setDisplayHomeAsUpEnabled(true)
            it.setDisplayShowHomeEnabled(true)
        }

        val taskId = intent.getStringExtra(AddEditTaskFragment.ARGUMENT_EDIT_TASK_ID)

        supportActionBar?.let {
            if (taskId == null) {
                it.title = "New To-Do"
            } else {
                it.title = "Edit To-Do"
            }
        }

        val addEditTaskFragment = getFragment(taskId)

        var shouldLoadDataFromRepo = true

        if (savedInstanceState != null) {
            shouldLoadDataFromRepo = savedInstanceState.getBoolean(SHOULD_LOAD_DATA_FROM_REPO_KEY)
        }

        addEditTaskPresenter = AddEditTaskPresenter(taskId, Injection.provideTasksRepository(applicationContext),
                addEditTaskFragment, shouldLoadDataFromRepo)
    }

    override fun onSaveInstanceState(outState: Bundle) {
        outState.putBoolean(SHOULD_LOAD_DATA_FROM_REPO_KEY, addEditTaskPresenter.isDataMissing)
        super.onSaveInstanceState(outState)
    }

    override fun onSupportNavigateUp(): Boolean {
        onBackPressed()
        return true
    }

    private fun getFragment(taskId: String?): AddEditTaskFragment {
        return supportFragmentManager.findFragmentById(R.id.contentFrame)
                as AddEditTaskFragment? ?: AddEditTaskFragment.newInstance().also {
            if (intent.hasExtra(AddEditTaskFragment.ARGUMENT_EDIT_TASK_ID)) {
                it.arguments = Bundle().apply {
                    putString(AddEditTaskFragment.ARGUMENT_EDIT_TASK_ID, taskId)
                }
            }
            ActivityUtils.addFragmentToActivity(supportFragmentManager, it, R.id.contentFrame)
        }
    }


    companion object {
        val SHOULD_LOAD_DATA_FROM_REPO_KEY = "SHOULD_LOAD_DATA_FROM_REPO_KEY"
        val REQUEST_ADD_TASK = 1
    }
}
